<template>
  <div class="qq-chat-container" style="height: 100%; width: 100%; display: flex; background-color: #f5f5f5; overflow: hidden; box-sizing: border-box;">
    <!-- 左侧联系人列表 (新增) -->
    <div class="contact-list" style="width: 280px; border-right: 1px solid #e6e6e6; background: #fff; overflow-y: auto; flex-shrink: 0;">
      <div class="search-box" style="padding: 10px; border-bottom: 1px solid #eee;">
        <el-input 
          placeholder="搜索联系人" 
          prefix-icon="el-icon-search"
          v-model="searchContact"
          clearable
        ></el-input>
      </div>
      
      <div class="contact-item" 
           v-for="item in filteredUserOptions" 
           :key="item.value"
           :class="{ 'active': wsForm.wsOppo === item.value }"
           @click="selectContact(item)"
           style="padding: 12px 15px; display: flex; align-items: center; cursor: pointer; border-bottom: 1px solid #f5f5f5; transition: background 0.2s;">
        <div class="avatar" style="width: 40px; height: 40px; border-radius: 50%; background-color: #409eff; color: white; display: flex; align-items: center; justify-content: center; margin-right: 10px; font-weight: bold;">
          {{ item.label ? item.label.charAt(0) : '?' }}
        </div>
        <div style="flex: 1; min-width: 0;">
          <div style="display: flex; justify-content: space-between;">
            <div class="name" style="font-weight: bold; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ item.label }}</div>
            <div class="time" style="font-size: 12px; color: #999; margin-left: 5px;">{{ getLastMessageTime(item.value) }}</div>
          </div>
          <div class="last-message" style="color: #666; font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
            {{ getLastMessageContent(item.value) }}
          </div>
        </div>
        <div v-if="hasUnreadMessages(item.value)" class="unread-badge" style="min-width: 20px; height: 20px; background-color: #f56c6c; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 12px;">
          {{ getUnreadCount(item.value) }}
        </div>
      </div>
    </div>

    <!-- 右侧聊天窗口 -->
    <div class="chat-window" style="flex: 1; display: flex; flex-direction: column; background: #fff; min-width: 0;">
      <!-- 顶部会话信息 -->
      <div class="chat-header" style="height: 60px; border-bottom: 1px solid #e6e6e6; display: flex; align-items: center; padding: 0 20px; background-color: #fff;">
        <el-button type="info" plain size="small" @click="backToOldVersion" style="margin-right: 15px; padding: 4px 12px; font-size: 13px;">
          返回旧版
        </el-button>
        <div class="avatar" style="width: 40px; height: 40px; border-radius: 50%; background-color: #67c23a; color: white; display: flex; align-items: center; justify-content: center; margin-right: 10px; font-weight: bold;">
          {{ selectedContact ? selectedContact.label.charAt(0) : '?' }}
        </div>
        <div style="flex: 1;">
          <div class="name" style="font-weight: bold; font-size: 16px;">{{ selectedContact ? selectedContact.label : '选择联系人' }}</div>
          <div class="status" style="color: #67c23a; font-size: 12px;" v-if="selectedContact">在线</div>
        </div>
        <div class="header-actions">
          <el-button type="text" icon="el-icon-phone" style="margin-right: 15px;"></el-button>
          <el-button type="text" icon="el-icon-video-camera" style="margin-right: 15px;"></el-button>
          <el-dropdown>
            <el-button type="text" icon="el-icon-more"></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click="cleanChatMsg">清空聊天记录</el-dropdown-item>
              <el-dropdown-item>消息免打扰</el-dropdown-item>
              <el-dropdown-item>查找聊天记录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>

      <!-- 消息内容区域 -->
        <div class="message-container" ref="messageContainer" style="flex: 1; overflow-y: auto; padding: 20px; background-color: #f5f7fa; min-height: 0;">
        <div v-if="msgList.length === 0" style="text-align: center; color: #999; margin-top: 50px;">
          暂无聊天记录，开始您的第一次对话吧！
        </div>
        
        <div v-for="(msg, index) in msgList" :key="index" style="margin: 15px 0;">
          <!-- 时间分隔线 -->
          <div v-if="showTimeDivider(index)" class="time-divider" style="text-align: center; margin: 10px 0;">
            <span style="display: inline-block; padding: 0 10px; background-color: #fff; border-radius: 12px; font-size: 12px; color: #999; border: 1px solid #eee;">
              {{ formatTimeDivider(msg.time) }}
            </span>
          </div>
          
          <!-- 对方消息 -->
          <div v-if="msg.type === 'oppo'" style="display: flex; align-items: flex-start; margin-left: 10px;">
            <div class="avatar" style="width: 36px; height: 36px; border-radius: 50%; background-color: #67c23a; color: white; display: flex; align-items: center; justify-content: center; margin-right: 10px; font-weight: bold;">
              {{ selectedContact ? selectedContact.label.charAt(0) : '?' }}
            </div>
            <div style="max-width: 70%;">
              <div class="message-bubble" style="background-color: #fff; border-radius: 4px 12px 12px 12px; padding: 10px 12px; box-shadow: 0 1px 2px rgba(0,0,0,0.1);">
                <div v-html="msg.content" class="w-e-text" style="font-size: 14px; line-height: 1.5;"></div>
              </div>
              <div class="message-meta" style="display: flex; align-items: center; margin-top: 4px; color: #999; font-size: 12px;">
                <span>{{ formatTime(msg.time) }}</span>
                <span v-if="msg.isRead === 3" style="margin-left: 5px; color: #67c23a;">已读</span>
              </div>
            </div>
          </div>
          
          <!-- 我的消息 -->
          <div v-else-if="msg.type === 'me'" style="display: flex; justify-content: flex-end; align-items: flex-start; margin-right: 10px;">
            <div style="max-width: 70%;">
              <div class="message-bubble" style="background-color: #409eff; border-radius: 12px 4px 12px 12px; padding: 10px 12px;">
                <div v-html="msg.content" class="w-e-text" style="font-size: 14px; line-height: 1.5;"></div>
              </div>
              <div class="message-meta" style="display: flex; align-items: center; justify-content: flex-end; margin-top: 4px; color: #999; font-size: 12px;">
                <span v-if="msg.isRead === 3" style="margin-right: 5px; color: #67c23a;">已读</span>
                <span>{{ formatTime(msg.time) }}</span>
              </div>
            </div>
            <div class="avatar" style="width: 36px; height: 36px; border-radius: 50%; background-color: #409eff; color: white; display: flex; align-items: center; justify-content: center; margin-left: 10px; font-weight: bold;">
              {{ user.name ? user.name.charAt(0) : '我' }}
            </div>
          </div>
          
          <!-- 系统消息 -->
          <div v-else style="text-align: center; margin: 15px 0;">
            <div class="system-message" style="display: inline-block; background-color: #eee; border-radius: 12px; padding: 5px 15px; font-size: 12px; color: #666;">
              {{ msg.content }}
            </div>
          </div>
        </div>
      </div>

      <!-- 消息输入区域 -->
      <div class="input-area" style="border-top: 1px solid #e6e6e6; padding: 10px 20px; background: #fff;">
        <div class="tool-bar" style="display: flex; margin-bottom: 10px; border-bottom: 1px solid #eee; padding-bottom: 8px; flex-shrink: 0;">
          <el-button type="text" icon="el-icon-picture" style="margin-right: 15px;"></el-button>
          <el-button type="text" icon="el-icon-video-camera" style="margin-right: 15px;"></el-button>
          <el-button type="text" icon="el-icon-document" style="margin-right: 15px;"></el-button>
          <el-button type="text" icon="el-icon-smile" style="margin-right: 15px;"></el-button>
          <div style="flex: 1;"></div>
          <el-button type="text" icon="el-icon-more" @click="toggleAdvancedSettings"></el-button>
        </div>
        
        <div id="editor" style="min-height: 80px; max-height: 200px; border: 1px solid #e6e6e6; border-radius: 4px; padding: 10px; margin-bottom: 10px; background: #fff; overflow: hidden;"></div>
        
        <div v-show="showAdvancedSettings" style="margin-bottom: 10px; padding: 10px; background: #f9f9f9; border-radius: 4px; border: 1px solid #eee; flex-shrink: 0;">
          <el-radio-group v-model="messageType" size="small">
            <el-radio label="chat">聊天消息</el-radio>
            <el-radio label="system">系统通知</el-radio>
          </el-radio-group>
        </div>
        
        <div style="display: flex; justify-content: flex-end; align-items: center;">
          <div style="margin-right: 15px; color: #999; font-size: 13px;" v-if="messageType === 'system'">
            当前为系统通知模式
          </div>
          <el-button type="primary" @click="sendChatMsg" style="padding: 8px 20px;">发送消息</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import E from 'wangeditor'
import hljs from 'highlight.js'

export default {
  name: 'WsChatNew',
  props: {
    opponentId: {
      type: String,
      required: false,
      default: '',
    },
  },
  inject: {
    getWebsocket: {
      default: () => () => null,
    },
  },
  data() {
    return {
      userOptions: [],
      userOptionsLoading: false,
      msgList: [],
      user: JSON.parse(localStorage.getItem('userInfo') || '{}'),
      wsForm: {
        wsOppo: '',
        content: '',
      },
      wsRules: {
        wsOppo: [
          {
            required: true,
            message: '请选择会话人',
            trigger: 'change',
          },
        ],
        content: [
          {
            required: true,
            message: '消息内容不能为空',
            trigger: 'blur',
          },
        ],
      },
      showTime: {},
      timers: {},
      messageType: 'chat',
      showAdvancedSettings: false,
      searchContact: '',
      lastMessageMap: {}, // 存储每个联系人的最后一条消息
      unreadCountMap: {}, // 存储每个联系人的未读消息数量
      editor: null,
    }
  },
  computed: {
    filteredUserOptions() {
      if (!this.searchContact) return this.userOptions;
      const searchLower = this.searchContact.toLowerCase();
      return this.userOptions.filter(item => 
        item.label.toLowerCase().includes(searchLower)
      );
    },
    selectedContact() {
      return this.userOptions.find(item => item.value === this.wsForm.wsOppo);
    }
  },
  mounted() {
        this.init();
        this.initUsersOptions();
        this.setupResponsive();
    },
  watch: {
    msgList: {
      handler() {
        this.$nextTick(() => {
          this.scrollToBottom();
          this.updateLastMessage();
        });
      },
      deep: true
    },
    'wsForm.wsOppo'(newVal) {
      if (newVal) {
        // 清空该联系人的未读消息
        this.$set(this.unreadCountMap, newVal, 0);
      }
    },
    '$route.query.opponentId': {
      handler(newVal) {
        if (newVal && this.userOptions.length > 0) {
          this.autoSelectOpponent();
        }
      },
      immediate: true
    },
    opponentId: {
      handler(newVal) {
        if (newVal && this.userOptions.length > 0) {
          this.autoSelectOpponent();
        }
      },
      immediate: true
    },
    userOptions: {
      handler(newOptions) {
        if (newOptions && newOptions.length > 0) {
          this.autoSelectOpponent();
        }
      },
      deep: true
    },
    'wsForm.wsOppo'(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.msgList = [];
        if (newVal && this.user) {
          this.fetchChatRecords(this.user.id, newVal);
        }
      }
    }
  },
  methods: {
        // 返回旧版聊天界面
        backToOldVersion() {
            this.$emit('switch-version');
        },
        
        // 监听窗口大小变化
        handleResize() {
            this.$nextTick(() => {
                this.scrollToBottom();
            });
        },
        
        // 组件挂载后设置适配
        setupResponsive() {
            window.addEventListener('resize', this.handleResize);
            // 初始调整
            this.$nextTick(() => {
                this.scrollToBottom();
            });
        },
    fetchChatRecords(userId, oppoId) {
      this.wsLoading = true;
      this.$request
        .get('/chat/getChatRecords', {
          params: {
            userId: userId,
            oppoId: oppoId,
          },
        })
        .then((res) => {
          if (res.code === '200') {
            this.msgList = res.data.map((item) => ({
              id: item.id,
              type: item.userId === this.user.id.toString() ? 'me' : 'oppo',
              content: item.content,
              time: item.creatTime,
              isRead: item.isRead
            }));
          } else {
            this.$message.error('获取聊天记录失败：' + res.msg);
          }
        })
        .catch((error) => {
          this.$message.error('网络错误，获取聊天记录失败');
        })
        .finally(() => {
          this.wsLoading = false;
        });
    },
    
    updateLastMessage() {
      if (this.wsForm.wsOppo && this.msgList.length > 0) {
        const lastMsg = this.msgList[this.msgList.length - 1];
        this.$set(this.lastMessageMap, this.wsForm.wsOppo, {
          content: this.stripHtml(lastMsg.content),
          time: lastMsg.time,
          isRead: lastMsg.isRead
        });
      }
    },
    
    stripHtml(html) {
      const tmp = document.createElement("DIV");
      tmp.innerHTML = html;
      return tmp.textContent || tmp.innerText || "";
    },
    
    getLastMessageContent(contactId) {
      const msg = this.lastMessageMap[contactId];
      return msg ? msg.content : '暂无消息';
    },
    
    getLastMessageTime(contactId) {
      const msg = this.lastMessageMap[contactId];
      return msg ? this.formatTime(msg.time) : '';
    },
    
    hasUnreadMessages(contactId) {
      return this.unreadCountMap[contactId] > 0;
    },
    
    getUnreadCount(contactId) {
      return this.unreadCountMap[contactId] || 0;
    },
    
    selectContact(item) {
      this.wsForm.wsOppo = item.value;
    },
    
    handleMouseEnter(index) {
      this.clearTimer(index);
      this.timers[index] = setTimeout(() => {
        this.$set(this.showTime, index, true);
      }, 3000);
    },
    
    handleMouseLeave(index) {
      this.clearTimer(index);
      this.$set(this.showTime, index, false);
    },
    
    markAsRead(index) {
      if (this.msgList[index].type === 'oppo' && this.msgList[index].isRead === 2) {
        this.$set(this.msgList[index], 'isRead', 3);
        this.sendReadStatusToServer(this.msgList[index]);
      }
    },
    
    handleReadAck(msg) {
      if (msg.oppo === this.user.id && msg.uid === this.wsForm.wsOppo) {
        const index = this.msgList.findIndex(
          (item) => item.id === msg.msgId && item.type === 'me'
        );
        if (index !== -1) {
          this.$set(this.msgList[index], 'isRead', 3);
        }
      }
    },
    
    handleRefresh(msg) {
      const index = this.msgList.findIndex(
        (item) => item.id === msg.id && item.type === 'me'
      );
      if (index !== -1) {
        this.$set(this.msgList[index], 'isRead', 3);
      }
    },
    
    sendReadStatusToServer(msg) {
      if (msg && msg.id) {
        this.$request
          .post('/chat/markAsRead', {
            recordId: msg.id,
          })
          .then((res) => {
            if (res.code === '200') {
              // 通知对方已读
            } else {
              this.$message.error('标记消息为已读失败：' + res.msg);
            }
          })
          .catch((error) => {
            this.$message.error('网络错误，标记消息为已读失败');
          });
      } else {
        console.warn('无法标记消息为已读：消息ID不存在');
      }
    },
    
    sendChatMsg() {
      if (this.editor) {
        this.wsForm.content = this.editor.txt.html();
      }
      
    //   this.$refs.wsForm.validate((valid) => {
    //     if (valid) {
          const connectionInfo = this.checkWebSocketConnection();
          if (!connectionInfo.connected) {
            this.$message.error(connectionInfo.description);
            console.warn('无法发送消息:', connectionInfo.description);
            this.reconnectWebSocket();
            return;
          }
          
          const websocket = this.getWebsocket();
          if (!websocket) {
            this.$message.error('WebSocket实例获取失败');
            console.error('getWebsocket()返回null');
            return;
          }
          
          let processedContent = this.wsForm.content;
          try {
            processedContent = processedContent.replace(/[\xF0-\xF7][\x80-\xBF]{3}/g, '');
          } catch (e) {
            console.error('处理内容时出错:', e);
          }
          
          const msg = {
            type: this.messageType,
            content: processedContent,
            uid: this.user.id,
            oppo: this.wsForm.wsOppo,
            from: this.user.name,
            to: this.userOptions.find(item => item.value === this.wsForm.wsOppo)?.label,
            isRead: 2,
            msgTime: new Date().toLocaleString(),
          };
          
          try {
            websocket.send(JSON.stringify(msg));
            if (this.msgList.length > 100) this.msgList.shift();
            this.wsForm.content = '';
            if (this.editor) {
              this.editor.txt.clear();
            }
            this.scrollToBottom();
          } catch (error) {
            console.error('发送消息失败:', error);
            this.$message.error('发送消息失败，请重试');
          }
        // }
    //   });
    },
    
    clearTimer(index) {
      if (this.timers[index]) {
        clearTimeout(this.timers[index]);
        this.timers[index] = null;
      }
    },
    
    toggleAdvancedSettings() {
      this.showAdvancedSettings = !this.showAdvancedSettings;
    },
    
    scrollToBottom() {
      const container = this.$refs.messageContainer;
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    },
    
    cleanChatMsg() {
      if (!this.wsForm.wsOppo || this.wsForm.wsOppo === '') {
        this.$message.warning('请先选择会话人');
        return;
      }
      
      this.$request.delete('/chat/cleanChatRecords', {
        params: {
          userId: this.user.id,
          oppoId: this.wsForm.wsOppo,
        },
      }).then((res) => {
        if (res.code === '200') {
          this.msgList = [];
          this.$message.success('聊天记录已清空');
        } else {
          this.$message.error('清空失败：' + res.msg);
        }
      }).catch((error) => {
        this.$message.error('网络错误，清空失败');
        console.error('清空聊天记录失败:', error);
      });
    },
    
    initUsersOptions() {
      this.userOptionsLoading = true;
      this.$request({
        method: 'GET',
        url: '/user/getSelect',
      }).then((res) => {
        if (res.code === '200') {
          this.userOptions = res.data;
          this.autoSelectOpponent();
        } else {
          this.$message.error(res.msg);
          return false;
        }
      }).finally(() => {
        this.userOptionsLoading = false;
      });
    },
    
    autoSelectOpponent() {
      const targetId = this.$route.query.opponentId || this.opponentId;
      if (!targetId) return;
      
      if (this.userOptions.length === 0) {
        console.warn('用户选项尚未加载完成，无法自动选择会话人');
        return;
      }
      
      const opponent = this.userOptions.find(
        (item) => String(item.value) === String(targetId)
      );
      
      if (opponent) {
        this.$nextTick(() => {
          this.wsForm.wsOppo = opponent.value;
          this.fetchChatRecords(this.user.id, opponent.value);
        });
      } else {
        console.warn(`未找到ID为 ${targetId} 的用户`);
        this.$message.warning(`未找到ID为 ${targetId} 的会话人`);
      }
    },
    
    sendInitMsg() {
      const connectionInfo = this.checkWebSocketConnection();
      if (!connectionInfo.connected) {
        console.warn('无法发送初始化消息:', connectionInfo.description);
        return;
      }
      
      const msg = {
        type: 'init',
        content: this.user.id + '号用户正在连接……',
        uid: this.user.id,
        oppo: '0',
      };
      
      try {
        const websocket = this.getWebsocket();
        websocket.send(JSON.stringify(msg));
        console.log('初始化消息发送成功');
      } catch (error) {
        console.error('发送初始化消息失败:', error);
        this.$message.error('初始化消息发送失败，请检查网络连接');
      }
    },
    
    init() {
      this.$nextTick(() => {
        this.initializeWebSocket();
        this.initializeEditor();
      });
    },
    
    initializeWebSocket() {
      const connectionInfo = this.checkWebSocketConnection();
      if (!connectionInfo.connected) {
        console.warn('WebSocket初始化失败:', connectionInfo.description);
        return;
      }
      
      const websocket = this.getWebsocket();
      if (!websocket) {
        console.error('无法获取WebSocket实例');
        return;
      }
      
      websocket.onopen = () => {
        console.log('WebSocket连接已建立');
        this.$message.success('WebSocket连接成功');
        this.sendInitMsg();
      };
      
      websocket.onerror = (error) => {
        console.error('WebSocket连接错误:', error);
        this.$message.error('WebSocket连接错误，请检查网络连接');
      };
      
      websocket.onclose = (event) => {
        console.log('WebSocket连接已关闭', event);
        this.$message.warning('WebSocket连接已断开');
      };
      
      if (websocket.readyState === WebSocket.OPEN) {
        console.log('WebSocket已处于连接状态，直接发送初始化消息');
        this.sendInitMsg();
      }
      
      websocket.onmessage = (event) => {
        this.handleWebSocketMessage(event);
      };
    },
    
      handleWebSocketMessage(event) {
        console.log("WsChat收到消息："+event.data);
      try {
        const msg = JSON.parse(event.data);
        console.log("WsChat收到消息："+msg);
        switch (msg.type) {
          case 'init':
            this.msgList.push({
              id: msg.id,
              type: msg.type,
              content: msg.content,
              time: new Date().toLocaleString(),
              isRead: msg.type === 'me' ? 3 : 2
            });
            this.scrollToBottom();
            break;
            
          case 'chat':
          case 'system': 
            const userOption = this.userOptions.find(
              (item) => item.value.toString() === msg.oppo
            );
            
            if (userOption) {
              const currentMsgList = [...this.msgList];
              this.wsForm.wsOppo = userOption.value;
              this.msgList = currentMsgList;
              
              // 更新未读消息计数
              if (this.wsForm.wsOppo !== userOption.value) {
                this.$set(this.unreadCountMap, userOption.value, 
                  (this.unreadCountMap[userOption.value] || 0) + 1);
              }
            } else {
              this.$message.warning('根据对方id没有找到对方名称');
            }
            
            this.msgList.push({
              id: msg.id,
              type: 'oppo',
              content: msg.content,
              time: new Date().toLocaleString(),
              isRead: 2
            });
            this.scrollToBottom();
            break;
            
          case 'chatMe':
            this.msgList.push({
              id: msg.id,
              type: 'me',
              content: msg.content,
              time: msg.msgTime,
              isRead: 2
            });
            break;
            
          case 'read_ack':
            this.handleReadAck(msg);
            break;
            
          case 'refresh':
            this.handleRefresh(msg);
            break;
            
          case 'success':
          case 'warning':
          case 'info':
          case 'error':
            this.$notify({
              title: '收到通知',
              message: msg.content,
              type: msg.type,
              duration: 3000,
            });
            break;
            
          default:
            this.$message.warning('未知消息类型');
        }
      } catch (error) {
        console.error('处理WebSocket消息失败:', error);
      }
    },
    
    initializeEditor() {
      if (this.editor) {
        this.editor.destroy();
        this.editor = null;
      }
      
      this.editor = new E(`#editor`);
      this.editor.highlight = hljs;
      
      this.editor.config.toolbar = [
        ['bold', 'italic', 'underline', 'strike'],
        ['link', 'image', 'video'],
        ['fontSize', 'fontName', 'foreColor', 'backColor'],
        ['alignLeft', 'alignCenter', 'alignRight', 'alignJustify'],
        ['list', 'todoList'],
        ['code', 'quote'],
        ['undo', 'redo'],
      ];
      
      this.editor.config.uploadImgServer = this.editorFileUpload;
      this.editor.config.uploadFileName = 'file';
      this.editor.config.uploadImgHeaders = {
        token: this.user.token,
      };
      this.editor.config.uploadImgParams = {
        type: 'img',
      };
      
      this.editor.config.uploadImgHooks = {
        customInsert: (insertImg, result, editor) => {
          console.log(result);
          if (result.errno === 0 && result.data?.length > 0) {
            const imgUrl = result.data[0].url.fileUrl?.trim();
            if (typeof imgUrl === 'string') {
              insertImg(imgUrl);
            } else {
              this.$message.error('图片URL格式不正确');
            }
          } else {
            this.$message.error(
              '图片上传失败：' + (result.msg || '无有效数据')
            );
          }
        },
      };
      
      this.editor.config.uploadVideoServer = this.editorFileUpload;
      this.editor.config.uploadVideoName = 'file';
      this.editor.config.uploadVideoHeaders = {
        token: this.user.token,
      };
      this.editor.config.uploadVideoParams = {
        type: 'video',
      };
      
      this.editor.create();
    },
    
    checkWebSocketConnection() {
      const websocket = this.getWebsocket();
      if (!websocket) {
        return {
          connected: false,
          readyState: null,
          readyStateText: 'WebSocket实例不存在',
          description: 'WebSocket实例为null，请检查网络连接或刷新页面'
        };
      }
      
      let readyStateText = '';
      switch (websocket.readyState) {
        case WebSocket.CONNECTING:
          readyStateText = '连接中';
          break;
        case WebSocket.OPEN:
          readyStateText = '已连接';
          break;
        case WebSocket.CLOSING:
          readyStateText = '关闭中';
          break;
        case WebSocket.CLOSED:
          readyStateText = '已关闭';
          break;
        default:
          readyStateText = '未知状态';
      }
      
      return {
        connected: websocket.readyState === WebSocket.OPEN,
        readyState: websocket.readyState,
        readyStateText: readyStateText,
        description: websocket.readyState === WebSocket.OPEN 
          ? 'WebSocket连接正常' 
          : `WebSocket当前状态：${readyStateText}，请稍后重试`
      };
    },
    
    reconnectWebSocket() {
      const connectionInfo = this.checkWebSocketConnection();
      if (!connectionInfo.connected) {
        this.$message.warning('WebSocket连接异常，正在尝试重新连接...');
        console.warn('WebSocket状态:', connectionInfo.description);
        
        this.$confirm('WebSocket连接已断开，是否刷新页面重新连接？', '连接提示', {
          confirmButtonText: '刷新页面',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          location.reload();
        }).catch(() => {
          console.log('用户取消刷新');
        });
        
        return false;
      }
      return true;
    },
    
    // 显示时间分隔线
    showTimeDivider(index) {
      if (index === 0) return true;
      
      const prevMsg = this.msgList[index - 1];
      const currentMsg = this.msgList[index];
      
      // 如果与上一条消息的时间间隔大于10分钟，显示时间分隔线
      const prevTime = new Date(prevMsg.time).getTime();
      const currentTime = new Date(currentMsg.time).getTime();
      return currentTime - prevTime > 600000;
    },
    
    // 格式化时间分隔线
    formatTimeDivider(time) {
      const date = new Date(time);
      const now = new Date();
      
      // 如果是今天
      if (date.toDateString() === now.toDateString()) {
        return '今天 ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
      }
      
      // 如果是昨天
      const yesterday = new Date(now);
      yesterday.setDate(yesterday.getDate() - 1);
      if (date.toDateString() === yesterday.toDateString()) {
        return '昨天 ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
      }
      
      // 其他日期
      return date.toLocaleDateString([], {year: 'numeric', month: 'short', day: 'numeric'}) 
        + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
    },
    
    // 格式化消息时间
    formatTime(time) {
      const date = new Date(time);
      const now = new Date();
      
      // 如果是今天
      if (date.toDateString() === now.toDateString()) {
        return date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
      }
      
      // 如果是昨天
      const yesterday = new Date(now);
      yesterday.setDate(yesterday.getDate() - 1);
      if (date.toDateString() === yesterday.toDateString()) {
        return '昨天 ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
      }
      
      // 其他日期
      return date.toLocaleDateString([], {year: 'numeric', month: 'short', day: 'numeric'}) 
        + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
    },
    
    // 消息文件上传方法
    editorFileUpload() {
      // 实际应用中需要实现文件上传逻辑
      return '/api/upload';
    }
  },
  beforeDestroy() {
        if (this.editor) {
            this.editor.destroy();
            this.editor = null;
        }
        window.removeEventListener('resize', this.handleResize);
    }
}
</script>

<style scoped>
.qq-chat-container {
  display: flex;
  height: 100%;
  width: 100%;
  min-height: 400px;
  font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial, "PingFang SC", "Microsoft YaHei", sans-serif;
  box-sizing: border-box;
  overflow: hidden; /* 防止整个容器出现滚动条 */
}

/* 确保弹窗能够自适应内容 */
.chat-window {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-header {
  flex-shrink: 0;
  /* 标题栏固定高度，不随内容变化 */
}

.message-container {
  flex: 1;
  /* 消息区域占据剩余空间 */
  overflow-y: auto;
  min-height: 300px;
  /* 确保有最小高度 */
}

.input-area {
  flex-shrink: 0;
  /* 输入区域固定高度，不随内容变化 */
}

/* 联系人列表样式 */
.contact-item.active {
  background-color: #e6f7ff;
  border-left: 3px solid #409eff;
}

.contact-item:hover {
  background-color: #f5f7fa;
}

.unread-badge {
  background-color: #f56c6c;
  color: white;
  border-radius: 50%;
  min-width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

/* 消息样式 */
.message-bubble {
  max-width: 70%;
  border-radius: 8px;
  padding: 8px 12px;
  position: relative;
}

.message-meta {
  font-size: 11px;
  color: #999;
  margin-top: 4px;
}

.time-divider {
  margin: 15px 0;
}

/* 富文本编辑器样式 */
::v-deep #editor {
  min-height: 120px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 10px;
  background: #fff;
}

::v-deep .w-e-text-container {
  height: auto !important;
  min-height: 80px;
  max-height: 200px;
}

::v-deep .w-e-toolbar {
  border-bottom: 1px solid #f1f1f1 !important;
  background-color: #fff !important;
}

::v-deep .w-e-text {
  padding: 10px !important;
  background-color: #fff !important;
  font-size: 14px !important;
  line-height: 1.5 !important;
}

::v-deep .w-e-text img {
  max-width: 100%;
  border-radius: 4px;
}

::v-deep .w-e-text video {
  max-width: 100%;
}

::v-deep .w-e-text pre {
  background-color: #f5f5f5;
  border-radius: 4px;
  padding: 8px;
  overflow-x: auto;
  font-family: monospace;
  font-size: 13px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .contact-list {
    width: 60px !important;
  }
  
  .contact-list .contact-item .name,
  .contact-list .contact-item .last-message,
  .contact-list .contact-item .time {
    display: none;
  }
  
  /* 在移动设备上优化标题栏布局 */
  .chat-header {
    padding: 0 10px;
  }
  
  .chat-header .el-button {
    margin-right: 8px;
    padding: 2px 8px;
    font-size: 12px;
  }
  
  .qq-chat-container {
    min-height: 500px;
  }
}
</style>